/**

 * User: sunil.incubator@yahoo.com
 * Date: Sep 20, 2009
 * Time: 12:51:36 AM
 */
package com.batchengine.action;

import com.batchengine.Definitions;
import static com.batchengine.Definitions.TaskType.PYTHON;
import static com.batchengine.util.EnvUtil.getConfFolderLocation;
import com.batchengine.util.LoggingFactory;
import static com.batchengine.util.ReflectionUtil.createObjectzForClaszzName;
import org.apache.log4j.Logger;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class ActionFactory {

    private static ActionFactory ourInstance = new ActionFactory();
    private Map<String, String> actionMap = new HashMap<String, String>();

    private static final Logger logger = LoggingFactory.createLogger();

    public static ActionFactory getInstance() {
        return ourInstance;
    }

    private ActionFactory() {
    }

    public Action createAction(Definitions.TaskType type) {

        String actionClazz = actionMap.get(type.toString());
        if (null == actionClazz) {
            loadActionClassMap();
        }
        actionClazz = actionMap.get(type.toString());
        return (Action) createObjectzForClaszzName(actionClazz);
    }

    private synchronized void loadActionClassMap() {

        Properties properties = new Properties();
        try {

            properties.load(new FileInputStream(String.format("%saction.properties", getConfFolderLocation())));
            Set<Object> keys = properties.keySet();
            for (Object o : keys) {
                if (null == properties.get(o)) {
                    continue;
                }
                actionMap.put(o.toString(), properties.get(o).toString());
            }
        } catch (IOException e) {
            logger.error("error loading action map", e);
        }
    }

    public static void main(String[] args) {

        Action action = ActionFactory.getInstance().createAction(PYTHON);
        System.out.println(action);
    }
}
